<?php
# @version SVN: $Id: category.class.inc 576 2012-03-24 17:39:01Z novachok $

class category extends data
{
   public $lt        = NULL;
   public $rt        = NULL;
   public $level     = NULL;
   public $parent    = NULL;
   public $childs    = NULL;
   public $templates = NULL;
   public $forwardin = FALSE;

   protected $main_table      = 'meccano_tree';
   protected $translate_table = 'meccano_tree_translate';


   public function __construct($data = NULL)
   {
      parent::__construct();
      
      if(!empty($data) && is_array($data))
      {
         $node = reset($data);

         $this->id        = $node['id'];
         $this->level     = $node['level'];
         $this->lt        = $node['lt'];
         $this->rt        = $node['rt'];
         $this->cdate     = $node['cdate'];
         $this->mdate     = $node['mdate'];
         $this->forwardin = (bool)$node['forwardin'];

         if(!empty($node['templates']))
         {
            $this->templates = unserialize($node['templates']);
         } else
         {
            $this->templates = array(
               'meta'   => 'inherit',
               'header' => 'inherit',
               'left'   => 'inherit',
               'center' => 'inherit',
               'right'  => 'inherit',
               'footer' => 'inherit'
            );
         }

         $FIELDS = fields::getInstance();
         $fields = $FIELDS->splitFields(array('node'=>$this->id, 'belong'=>'c'));
         $this->loadEmpty($fields);

         $langs = request::getLang('all');

         foreach($langs AS $l)
         {
            if(!empty($data[$l['id']]))
            {
               foreach($data[$l['id']] AS $key=>$value)
               {
                  if(property_exists($this->_data, $key))
                  {
                     $this->_data->{$key}->normalizeValue($value, $l['id']);
                  }
               }
            }
         }
      } elseif(is_numeric($data))
      {
         $this->parent = ($data == 0 ? NULL : $data);
         $FIELDS = fields::getInstance();
         $fields = $FIELDS->splitFields(array('node'=>$data, 'belong'=>'c', 'active'=>TRUE));
         $this->loadEmpty($fields);
      }
   }


   public function save($data)
   {
      $sql = parent::save($data);
      if(empty($sql['main'])) return FALSE;

      $DB = database::getInstance();
      $sql_main = '';

      if(empty($this->id))
      {
         $sql['main'][] = '`lt` = '. (is_numeric($this->lt) ? $this->lt : 1);
         $sql['main'][] = '`rt` = '. (is_numeric($this->rt) ? $this->rt : 2);
         $sql['main'][] = '`level` = '. (is_numeric($this->level) ? $this->level : 1);
         $sql['main'][] = '`cdate` = NOW()';
         $sql_main = 'INSERT INTO `'. $this->main_table .'` SET'. implode(', ', $sql['main']);
      } else
      {
         $sql_main = 'UPDATE `'. $this->main_table .'` SET'. implode(', ', $sql['main']) .' WHERE `id` = '. $this->id;
         
      }
//echo $sql_main;

      $DB->DB_StartTransaction();
      $DB->sql = $sql_main;
      $DB->DB_Query();

      if(empty($this->id))
      {
         $this->id = $DB->DB_LastID();
      }

      foreach($sql['translate'] AS $l => $sql_translate)
      {
         $sql_translate  = 'INSERT INTO `'. $this->translate_table .'` SET `id` = '. $this->id .', `lang` = '. $l .', '. implode(', ', $sql_translate) .
                 ' ON DUPLICATE KEY UPDATE '. implode(', ', $sql_translate);
//echo "<br /><br />". $sql_translate; exit();
         $DB->sql = $sql_translate;
         $DB->DB_Query();
      }

      if($DB->DB_EndTransaction())
      {
         $this->saveFieldsets($data);
         return $this;
      }

      return FALSE;
   }

   public function getFields($alias = null, $tab = null)
   {
      $node   = !empty($this->id) ? $this->id : (!empty($this->parent) ? $this->parent : 0);
      $filter = array('belong'=>'c', 'active'=>TRUE);
      return parent::getFields($node , $filter);
   }

   public function href()
   {
      if(!empty($this->_href)) return $this->_href;

      $this->_href = substr($this->url(), 0, -1) .'.html';

      return $this->_href;
   }

   public function url()
   {
      if(!empty($this->_url)) return $this->_url;
      
      $lang = request::getLang('current');
      $this->_url = $lang['baseurl'];

      if(!empty($this->parent))
      {
         $path = tree_static::getPath($this->parent);
         if(!empty($path))
         {
            foreach($path AS $node)
            {
               $this->_url .= $node->alias .'/';
            }
         }
      }

      $this->_url .= $this->alias .'/';

      if($this->forwardin && !empty($this->childs))
      {
         $ch = reset($this->childs);
         $this->_url .= $ch->alias .'/';
      }

      return $this->_url;
   }


   /**
    * Get Path for current node
    * 
    * @return array
    */
   public function path()
   {
      if(!empty($this->id))
      {
         return tree_static::getPath($this->id);
      }

      return array();
   }

   /**
    * Count articles in given node and all subnodes if they are commonly accessed
    *
    * @return integer
    */
   public function countArticles()
   {
      if(empty($this->id)) return FALSE;
      $DB     = database::getInstance();

      $ids = tree_static::getChildrenId($this->id);
      $ids = !empty($ids) ? array_merge(array($this->id), $ids) : array($this->id);

      $DB->sql = 'SELECT COUNT(*) AS `articles` 
         FROM `meccano_articles` AS `t1`, `meccano_articles_translate` AS `t2`
         WHERE `t1`.`id` = `t2`.`id`
         AND `t1`.`deleted` IS NULL
         AND `t1`.`active` = "1"
         AND `t2`.`lang` = '. request::getLang('currentId') .'
         AND `t1`.`cat` IN ('. implode(', ', $ids) .')';
      $DB->DB_Query();

      return $DB->DB_GetResult(0, 'articles');
   }
}